import router from '../router';

export default{
    state:{
        status: false,
        userInfo:{
            userId: '',
            username: '',
            nickname: '',
            sex: '',
            avatar:''
        } 
    },

    getters:{
        userInfo(state){
            //先从store即内存中获取，获取不到则到localStory取
            try {
                const status = state.status;
                return status?state.userInfo:JSON.parse(localStorage.getItem('userInfo'));
            } catch (error) {
                console.log(error);
                return {
                    userId: null,
                    username: null,
                    nickname: null,
                    sex: null,
                    avatar:null
                }
            }
        }
    },

    mutations:{
        setUserInfo(state,userInfo){
            state.status = true;
            state.userInfo = JSON.parse(JSON.stringify(userInfo));

            try {
                localStorage.setItem('userInfo',JSON.stringify(state.userinfo));
            } catch (error) {
                router.app.$message.error('发生异常，请重新登录');
                router.push('/login');
            }
        },

        removeUserInfo(state){
            state.status = false;
            state.userInfo = null;
            localStorage.removeItem('userInfo');
        }
    }
}